

package tomkitty;

import java.util.*;
import java.io.*;
import java.net.*;

public class TkVHostHandler extends Turdlet
  implements VHostHandler {

  protected static Properties vhosts = null;
  protected Configuration config;

  public Handler init(Handler handler, AppContext context) {
    super.init(handler, context);

    config = context.getConfig();

    if (vhosts == null) {
      vhosts = new Properties();

      Debug.p("Loading virtual hosts:");
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(config.get(CONF_VHOST_CONFIG)); 
        
        vhosts.loadFromXML(fis);
        fis.close();

        Enumeration i = vhosts.propertyNames();
        while (i.hasMoreElements()) {
          String name = (String) i.nextElement();
          Debug.p("loaded '"+vhosts.getProperty(name)+"' on host '"+name+"'");
        }
      } catch (Exception e) {
        Debug.e("can't load config: " + e.getMessage());
        try {
          fis.close();
        } catch (Exception o_e) {
        }
      }
      Debug.p("");
    }

    return this;
  }

  public void doit() {
    URI uri = request.getUri();

    String host = uri.getAuthority();
    String hostNoPort = host.split(":")[0];

    String appname = null;
    if ( (appname = vhosts.getProperty(host)) != null ||
         (appname = vhosts.getProperty(hostNoPort)) != null ) {
      String path = uri.getPath();

      if (! path.startsWith("/" + appname + "/")) {
        String scheme = uri.getScheme() + "://";
        String query = (uri.getQuery() == null ? "" : "?" + uri.getQuery());
        String fragment = 
          (uri.getFragment() == null ? "" : "#" + uri.getFragment());

        path = "/" + appname + path;

        try {
          request.setUri(new URI(scheme + host + path + query + fragment));
        } catch (Exception e) {
          e.printStackTrace();
          response.setStatus(HTTP_SERVER_ERROR);
        }
      }
    }
  }

}
